package com.solution.admin.sysconfig.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.solution.admin.sysconfig.entity.WechatArticleEntity;
import com.solution.admin.sysconfig.entity.WechatMsgConfigEntity;
import com.solution.admin.sysconfig.entity.WechatMsgMassSendingEntity;
import com.solution.admin.sysconfig.service.WechatMsgConfigService;
import com.solution.admin.sysconfig.service.WechatMsgMassSendingService;
import com.solution.common.config.PublicConfig;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.core.constants.WechatConstants.MsgTypeEnum;
import com.solution.wx.core.entity.sendmsg.ArticleEntity;
import com.solution.wx.core.entity.sendmsg.ArticlesEntity;
import com.solution.wx.core.entity.sendmsg.SendMsgParamEntity;
import com.solution.wx.core.util.WechatUtil;

/**
 * 微信消息群发管理web控制层
 * @author solin
 * @date 2017-11-30 14:45:04
 */
@RequestMapping("/wechatMsgMassSending")
@Controller
public class WechatMsgMassSendingController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(WechatMsgMassSendingController.class);

	@Autowired
	private WechatMsgMassSendingService wechatMsgMassSendingService;
	@Autowired
	private WechatMsgConfigService wechatMsgConfigService;
	
	/**
	 * 跳转微信消息群发管理查询页面
	 * @param WechatMsgMassSending 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
 	 * @date 2017-11-30 14:45:04
	 */
	@RequestMapping("/toListWechatMsgMassSendingPage")
	public String toListWechatMsgMassSendingPage(WechatMsgMassSendingEntity wechatMsgMassSending, HttpServletRequest request) {
		return "sysconfig/wechatMsgMassSending_list";
	}

	/**
	 * 分页查询微信消息群发管理列表
	 * @param wechatMsgMassSending 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
 	 * @date 2017-11-30 14:45:04
	 */
	@RequestMapping("/listWechatMsgMassSendingPage")
	@ResponseBody
	public JSONGrid listWechatMsgMassSendingPage(WechatMsgMassSendingEntity wechatMsgMassSending, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap.put("beginTime", request.getParameter("beginTime"));
			paramMap.put("endTime", request.getParameter("endTime"));
			
			PageBean pageBean = wechatMsgMassSendingService.listWechatMsgMassSendingPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询微信消息群发管理失败", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author solin
 	 * @date 2017-11-30 14:45:04
	 */
	@RequestMapping("/toAddWechatMsgMassSending")
	public String toAddWechatMsgMassSending(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		return "sysconfig/wechatMsgMassSending_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author solin
 	 * @date 2017-11-30 14:45:04
	 */
	@RequestMapping("/toUpdateWechatMsgMassSending")
	public String toUpdateWechatMsgMassSending(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			WechatMsgMassSendingEntity wechatMsgMassSending = wechatMsgMassSendingService.getWechatMsgMassSendingById(id);
			request.setAttribute("wechatMsgMassSending", wechatMsgMassSending);
		} catch (Exception e) {
			handleException("跳转编辑微信消息群发管理页面错误", logger, e);
		}
		return "sysconfig/wechatMsgMassSending_form";
	}


	/**
	 * 新增或保存微信消息群发管理
	 * @param request 请求对象
	 * @param wechatMsgMassSendingEntity 微信消息群发管理实体
	 * @return
	 * @author solin
 	 * @date 2017-11-30 14:45:04
	 */
	@RequestMapping("/saveOrUpdateWechatMsgMassSending")
	@ResponseBody
	public Map<String, Object> saveWechatMsgMassSending(HttpServletRequest request, WechatMsgMassSendingEntity wechatMsgMassSendingEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			String id = request.getParameter("id");
			if(StringUtil.isNotEmpty(id)){
				result = wechatMsgMassSendingService.updateWechatMsgMassSending(wechatMsgMassSendingEntity);
			}else{
				result = (int)wechatMsgMassSendingService.saveWechatMsgMassSending(wechatMsgMassSendingEntity);
			}
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("添加微信消息群发管理失败", logger, e);
		}
		return resultMap;
	}
	
	/**
	 * 群发消息
	 * @param request
	 * @param wechatMsgMassSendingEntity
	 * @param openIds
	 * @return
	 * @author: solin
	 * @date: 2017年12月5日 下午4:47:59
	 */
	@RequestMapping("/massSendingMessage")
	@ResponseBody
	public Map<String, Object> massSendingMessage(HttpServletRequest request, WechatMsgMassSendingEntity wechatMsgMassSendingEntity, String openIds) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		resultMap.put(PublicStatus.RESULT_CODE, result);
		try {
			if (StringUtil.isEmpty(openIds)) {
				return resultMap;
			}
			JSONObject sendMsgResObj = null;
			
			//获取将要发送的消息
			Long msgId = wechatMsgMassSendingEntity.getMsgId();
			WechatMsgConfigEntity msgEntity = wechatMsgConfigService.getWechatMsgConfigById(msgId);
			
			String[] openIdArray = openIds.split(",");
			
			SendMsgParamEntity param = new SendMsgParamEntity();
			param.setSendMode("openId"); //openId tag openIdpreview tagpreview delete
			param.setTouser(openIdArray);
			param.setIs_to_all(true);
			
			//消息类型
			String msgType = msgEntity.getMsgType();
			if ("1".equals(msgType)) { //文字消息
				param.setMsgtype(MsgTypeEnum.TEXT);
				param.setContent(msgEntity.getTextMessage());
				//发送消息
				sendMsgResObj = WechatUtil.sendNews(param, WechatUtil.getAccessToken());
			} else if ("2".equals(msgType)) { //图片消息
				String media_id = msgEntity.getImageMediaId();
				param.setMsgtype(MsgTypeEnum.IMAGE);
				param.setMedia_id(media_id);
				//发送消息
				sendMsgResObj = WechatUtil.sendNews(param, WechatUtil.getAccessToken());
			} else if ("3".equals(msgType)) { //图文消息
				String article_media_id = msgEntity.getArticleMediaId();
				if (StringUtil.isNotEmpty(article_media_id)) {
					//第三步:根据OpenID列表群发
					param.setMsgtype(MsgTypeEnum.ARTICLE);
					param.setMedia_id(article_media_id);
					param.setSend_ignore_reprint(1); //图文消息被判定为转载时，是否继续群发。 1为继续群发（转载），0为停止群发。
					//发送消息
					sendMsgResObj = WechatUtil.sendNews(param, WechatUtil.getAccessToken());
				}
			}
			
			if (sendMsgResObj.containsKey("errcode")) {
				if (sendMsgResObj.getInteger("errcode") != 0) {
					logger.error("发送失败 errcode:{}, errmsg:{} ", sendMsgResObj.getInteger("errcode"), sendMsgResObj.getString("errmsg"));  
				} else {
					result = 1;
				}
			}
			
			//消息发送后，将发送记录保存到数据库
			wechatMsgMassSendingEntity.setStatus(result);
			wechatMsgMassSendingEntity.setCreater(this.getUserCode());
			result = (int)wechatMsgMassSendingService.saveWechatMsgMassSending(wechatMsgMassSendingEntity);
			
			resultMap.put(PublicStatus.RESULT_CODE, result > 0 ? 1 : 0);
			resultMap.put(PublicStatus.RESULT_MSG, "发送成功");
		} catch (Exception e) {
			handleException("添加微信消息群发管理失败", logger, e);
		}
		return resultMap;
	}
	
}
